// 预览图和懒加载
import defaultImg from "@/assets/img-default.svg"
import errorImg from "@/assets/img-error.svg"
const thumb = {
    mounted: (el: any, binding: any, vnode: any) => {
        if (!binding.value) return;

        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    // 当图片进入视口时
                    el.src = defaultImg;
                    let img: any = new Image();
                    img.src = matchThumb(binding.value);
                    el.dataset.thumb = defaultImg;

                    // 将 img 绑定到元素上，以便在 unmounted 时取消加载
                    el._img = img;

                    img.onload = () => {
                        // 加载图片
                        el.dataset.thumb = matchThumb(binding.value);
                        el.src = matchThumb(binding.value);
                        img = null;
                        setTimeout(() => {
                            nodeReady(vnode, el);
                            loadImg(el, binding, vnode);
                        }, 0);
                    };

                    img.onerror = () => {
                        // 加载图片失败
                        img = null;
                        loadImg(el, binding, vnode);
                    };

                    observer.unobserve(el); // 停止观察
                }
            });
        });

        observer.observe(el); // 开始观察

        // 将 observer 绑定到元素上，以便在 unmounted 时清理
        el._observer = observer;
    },
    unmounted: (el: any) => {
        // 清理 IntersectionObserver
        if (el._observer) {
            el._observer.disconnect(); // 停止所有观察
            el._observer = null;
        }

        // 取消图片加载
        if (el._img) {
            el._img.src = ''; // 取消图片加载
            el._img = null;
        }

        // 取消第二张图片加载
        if (el._img2) {
            el._img2.src = ''; // 取消图片加载
            el._img2 = null;
        }
    },
};

export default thumb;

function loadImg(el: any, binding: any, vnode: any) {
    let img2: any = new Image();
    img2.src = binding.value;

    // 将 img2 绑定到元素上，以便在 unmounted 时取消加载
    el._img2 = img2;

    // 监听加载成功
    img2.onload = () => {
        el.dataset.thumb = binding.value;
        setTimeout(() => {
            el.src = binding.value;
            img2 = null;
        }, 0);
    };

    // 监听加载失败
    img2.onerror = () => {
        img2 = null;
        el.src = errorImg;
        nodeReady(vnode, el);
    };
}

function nodeReady(vnode: any, el: any) {
    if (vnode && vnode.props && vnode.props['data-ready']) {
        vnode.props['data-ready'](el)
    }
}
function matchThumb(val: any) {
    return val.replace('.png', '_thumb.png').replace('.jpg', '_thumb.jpg')
}